package com.example.demo.task;

import com.example.demo.data.db.TaskProcessResult;
import java.util.List;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Service;


/**
 * @author     jiangjinwu
 * @since 2025/10/9 23:25
 * @version 1.0
 */

@Slf4j
@Service
public class CorrectOrderTaskServiceImpl {

  @Autowired
  NamedParameterJdbcTemplate namedParameterJdbcTemplate ;
  private void doBatchUpdate(List<TaskProcessResult> results) {
    String sql = "UPDATE t_correct_task SET status = :code, message = :message, traceid = :traceId, finish_at = :finishAt WHERE id = :id";
    SqlParameterSource[] batchParams = results.stream()
        .map(BeanPropertySqlParameterSource::new)
        .toArray(SqlParameterSource[]::new);

    try {
      namedParameterJdbcTemplate.batchUpdate(sql, batchParams);
      logger.info("批量更新了 {} 条任务记录", results.size());
    } catch (Exception e) {
      logger.error("批量更新数据时发生异常", e);
      // 如果批量更新失败，回退到单条更新
      fallbackToSingleUpdate(results);
    }
  }

  /**
   * 当批量更新失败时，回退到单条更新
   */
  private void fallbackToSingleUpdate(List<TaskProcessResult> results) {
    String singleSql = "UPDATE t_correct_task SET status = :code, message = :message, traceid = :traceId, finish_at = :finishAt WHERE id = :id";
    for (TaskProcessResult result : results) {
      try {
        BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(result);
        namedParameterJdbcTemplate.update(singleSql, params);
      } catch (Exception e) {
        logger.error("单条更新任务ID={}时发生异常", result.getId(), e);
      }
    }
  }
}
